package com.zd.controller;

import com.github.pagehelper.PageInfo;
import com.zd.model.*;
import com.zd.service.*;
import com.zd.utils.DateUtil;
import com.zd.utils.ExcelUtil;
import com.zd.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/workInfo")
public class WorkInfoController extends BaseController {


    @Autowired
    private IWorkInfoService workInfoService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IAdministrativeDistrictService administrativeDistrictService;

    @Autowired
    private IEnterpriseLocationService enterpriseLocationService;

    @Autowired
    private IUnitsNatureService unitsNatureService;

    @Autowired
    private ICooperativeTypeService cooperativeTypeService;

    @Autowired
    private IScaleService scaleService;

    @Autowired
    private IForeignPropertyService foreignPropertyService;

    @Autowired
    private IProjectTypeService projectTypeService;


    //读取配置文件获取上传文件夹路径
    @Value("${upload.uploadPath}")
    private String uploadPath;

    /**
     * 企业信息查询
     *
     * @return
     */
    @RequestMapping(value = "/queryWorkInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public String queryWorkInfo(@RequestParam(name = "pageNum", required = false, defaultValue = "1")
                                        int pageNum,
                                @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                                        int pageSize, @RequestParam Map<String, Object> queryMap, Model model) {

        /*//添加录入人查询条件,排除部门为11的用户人员，其他只能看到自己提交的数据
        HttpSession session = getSession();
        UserInfo userInfo=(UserInfo) session.getAttribute("userInfo");-
        if(userInfo.getDepartmentid()!=11){
            queryMap.put("enteruserid",userInfo.getId());
        }*/

        List<WorkInfo> workInfoList = workInfoService.selectWorkInfo(pageNum, pageSize, queryMap);

        model.addAttribute("pageInfo", new PageInfo<>(workInfoList));
        model.addAttribute("workInfoList", workInfoList);
        model.addAttribute("queryMap", queryMap);

        return "workInfoIndex";
    }

    /**
     * 跳转企业信息添加页面
     *
     * @return
     */
    @GetMapping("/toWorkInfoAdd")
    public String toWorkInfoAdd() {
        return "workInfoAdd";
    }

    /**
     * 企业统计
     *
     * @param statisticsMap
     * @return
     */
    @ResponseBody
    @PostMapping("/selectWorkInfoStatistics")
    public List<WorkInfoStatistics> selectWorkInfoStatistics(@RequestParam Map<String, Object> statisticsMap) {

        return workInfoService.selectWorkInfoStatistics(statisticsMap);
    }

    @GetMapping("/workInfoStatistics")
    public String WorkInfoStatistics() {
        return "workInfoStatistics";
    }


    //查询到期
    @ResponseBody
    @GetMapping("/selectMaturity")
    public List<WorkInfo> selectMaturity() {
        return workInfoService.selectMaturity();
    }


    /**
     * 企业添加信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/workInfoAdd")
    public boolean workInfoAdd(WorkInfo workInfo) {

        //获取多协议文件
        List<MultipartFile> agreementUploadList = workInfo.getAgreementUpload();

        if (agreementUploadList != null && agreementUploadList.size() != 0) {

            //文件上传
            String uploadNewFileName = FileUtil.uploadFile(agreementUploadList, uploadPath);


            //存入数据库上传文件名
            workInfo.setAgreementurl(uploadNewFileName);
        }


        //企业法人资质
        MultipartFile legalPersonCertificateUpload = workInfo.getLegalPersonCertificateUpload();

        if (legalPersonCertificateUpload != null && !legalPersonCertificateUpload.isEmpty()) {

            String uploadNewFileName = FileUtil.uploadFileSingle(legalPersonCertificateUpload, uploadPath);

            //存入数据库上传文件名
            workInfo.setLegalPersonCertificateURL(uploadNewFileName);

        }

        //营业执照
        MultipartFile businessLicenseUpload = workInfo.getBusinessLicenseUpload();

        if (businessLicenseUpload != null && !businessLicenseUpload.isEmpty()) {
            String uploadNewFileName = FileUtil.uploadFileSingle(businessLicenseUpload, uploadPath);

            //存入数据库上传文件名
            workInfo.setBusinessLicenseURL(uploadNewFileName);
        }


        //入库时间
        workInfo.setEntertime(new Date());

        //录入用户id
        HttpSession session = getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");

        workInfo.setEnteruserid(userInfo.getId());

        //插入工作信息表
        workInfoService.insertSelective(workInfo);


        return true;

    }

    /**
     * 查看详细
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("toWorkInfoDetail")
    public String toWorkInfoDetail(int id, Model model) {

        WorkInfo workInfo = workInfoService.selectWorkInfoById(id);

        model.addAttribute("workInfo", workInfo);

        return "workInfoDetail";

    }

    /**
     * 下载文件
     *
     * @param response
     * @param fileName
     */
    @GetMapping("downloadFile")
    public void downloadFile(HttpServletResponse response, String fileName) {

        FileUtil.downloadFile(response, uploadPath, fileName);


    }


    /**
     * 跳转修改页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("toWorkInfoUpdate")
    public String toWorkInfoUpdate(int id, Model model) {


        WorkInfo workInfo = workInfoService.selectWorkInfoById(id);

        model.addAttribute("workInfo", workInfo);

        return "workInfoUpdate";
    }


    /**
     * 企业修改信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/workInfoUpdate")
    public boolean workInfoUpdate(WorkInfo workInfo) {

        //获取多协议文件
        List<MultipartFile> agreementUploadList = workInfo.getAgreementUpload();

        if (agreementUploadList != null && agreementUploadList.size() != 0) {

            //文件上传
            String uploadNewFileName = FileUtil.uploadFile(agreementUploadList, uploadPath);


            //存入数据库上传文件名
            workInfo.setAgreementurl(uploadNewFileName);
        }

        //企业法人资质上传
        MultipartFile legalPersonCertificateFile = workInfo.getLegalPersonCertificateUpload();

        if (legalPersonCertificateFile != null && !legalPersonCertificateFile.isEmpty()) {

            String uploadFileSingle = FileUtil.uploadFileSingle(legalPersonCertificateFile, uploadPath);

            workInfo.setLegalPersonCertificateURL(uploadFileSingle);

        }

        //营业执照上传
        MultipartFile businessLicenseUpload = workInfo.getBusinessLicenseUpload();

        if (businessLicenseUpload != null && !businessLicenseUpload.isEmpty()) {

            String uploadFileSingle = FileUtil.uploadFileSingle(businessLicenseUpload, uploadPath);

            workInfo.setBusinessLicenseURL(uploadFileSingle);

        }


        workInfoService.updateSelective(workInfo);

        return true;
    }

    /**
     * 删除合作内容
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("deleteCooperativeContentRel")
    public boolean deleteCooperativeContentRel(int id) {

        workInfoService.deleteCooperativeContentRel(id);

        return true;
    }


    /**
     * 删除合作协议
     *
     * @return
     */
    @ResponseBody
    @GetMapping("deleteAgreementurlName")
    public boolean deleteAgreementurlName(int id, String deleteAgreementurlName) {

        workInfoService.deleteAgreementurlName(id, deleteAgreementurlName);

        return true;

    }

    /**
     * 删除企业法人资质
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("deleteLegalPersonCertificate")
    public boolean deleteLegalPersonCertificate(int id) {

        workInfoService.deleteLegalPersonCertificate(id);


        return true;
    }

    /**
     * 删除营业执照资质
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("deleteBusinessLicense")
    public boolean deleteBusinessLicense(int id) {

        workInfoService.deleteBusinessLicense(id);

        return true;
    }


    /**
     * 物理删除企业资质
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("deleteQualifications")
    public boolean deleteQualifications(int id) {

        workInfoService.deleteQualifications(id);

        return true;
    }

    /**
     * 逻辑删除校企信息表
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("deleteWorkInfo")
    public boolean deleteWorkInfo(int id) {

        workInfoService.deleteWorkInfo(id);

        return true;
    }

    //设置消除到期提醒
    @ResponseBody
    @GetMapping("eliminateReminding")
    public boolean eliminateReminding(int id) {
        workInfoService.eliminateReminding(id);
        return true;
    }


    /**
     * 导出excel
     *
     * @param queryMap
     * @return
     */

    @PostMapping("exportExcel")
    public void exportExcel(@RequestParam Map<String, Object> queryMap, HttpServletResponse response) {

        //标题
        String titleName = "校企合作工作台账(以";

        //excel拼查询条件
        //承办部门
        if (queryMap.get("departmentid") != null && Integer.valueOf((String) queryMap.get("departmentid")).intValue() != -1) {

            Department department = departmentService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("departmentid")).intValue());
            titleName += "承办部门是" + department.getDepartment() + ",";
        }
        //合作单位名称
        if (queryMap.get("unitscooperativename") != null && !queryMap.get("unitscooperativename").equals("")) {

            titleName += "合作单位名称是" + queryMap.get("unitscooperativename") + ",";
        }
        //合作单位性质
        if (queryMap.get("unitsnatureid") != null && Integer.valueOf((String) queryMap.get("unitsnatureid")).intValue() != -1) {

            UnitsNature unitsNature = unitsNatureService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("unitsnatureid")).intValue());

            titleName += "合作单位性质是" + unitsNature.getName() + ",";

        }
        //企业类型
        if (queryMap.get("cooperativetypeid") != null && Integer.valueOf((String) queryMap.get("cooperativetypeid")).intValue() != -1) {
            CooperativeType cooperativetype = cooperativeTypeService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("cooperativetypeid")).intValue());

            titleName += "企业类型是" + cooperativetype.getType() + ",";
        }

        //企业规模
        if (queryMap.get("scaleid") != null && Integer.valueOf((String) queryMap.get("scaleid")).intValue() != -1) {
            Scale scale = scaleService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("scaleid")).intValue());

            titleName += "企业规模是" + scale.getScale() + ",";
        }
        //外资属性
        if (queryMap.get("foreignpropertyid") != null && Integer.valueOf((String) queryMap.get("foreignpropertyid")).intValue() != -1) {
            ForeignProperty foreignproperty = foreignPropertyService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("foreignpropertyid")).intValue());

            titleName += "外资属性是" + foreignproperty.getProperty() + ",";
        }

        //行政区属
        if (queryMap.get("administrativedistrictid") != null && Integer.valueOf((String) queryMap.get("administrativedistrictid")).intValue() != -1) {

            AdministrativeDistrict administrativeDistrict = administrativeDistrictService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("administrativedistrictid")).intValue());
            titleName += "行政区属是" + administrativeDistrict.getAdministrativedistrict() + ",";
        }

        //企业所在地
        if (queryMap.get("enterpriselocationid") != null && Integer.valueOf((String) queryMap.get("enterpriselocationid")).intValue() != -1) {

            EnterpriseLocation enterpriseLocation = enterpriseLocationService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("enterpriselocationid")).intValue());
            titleName += "企业所在地是" + enterpriseLocation.getEnterpriselocation() + ",";
        }

        //是否签署合作协议
        if (queryMap.get("signagreement") != null && Integer.valueOf((String) queryMap.get("signagreement")).intValue() != -1) {
            if (Integer.valueOf((String) queryMap.get("signagreement")).intValue() == 1) {
                titleName += "是否签署合作协议是 是,";
            } else if (Integer.valueOf((String) queryMap.get("signagreement")).intValue() == 2) {
                titleName += "是否签署合作协议是 否,";

            }
        }
        //项目分类
        if (queryMap.get("projecttypeid") != null && Integer.valueOf((String) queryMap.get("projecttypeid")).intValue() != -1) {
            ProjectType projecttype = projectTypeService.selectByPrimaryKey(Integer.valueOf((String) queryMap.get("projecttypeid")).intValue());
            titleName += "项目分类是" + projecttype.getProjecttype() + ",";
        }
        //协议签署开始时间
        if (queryMap.get("beginSignagreement") != null && !queryMap.get("beginSignagreement").equals("")) {
            titleName += "协议签署开始时间是" + queryMap.get("beginSignagreement") + ",";
        }

        //协议签署终止时间
        if (queryMap.get("endSignagreement") != null && !queryMap.get("endSignagreement").equals("")) {
            titleName += "协议签署终止时间是" + queryMap.get("endSignagreement") + ",";
        }

        titleName += "来统计)";


        //列名
        String[] columnName = {"承办部门", "合作单位性质", "合作单位名称", "企业类型", "企业规模",
                "外资属性", "行政区属", "企业所在地", "企业联系人及联系方式", "是否签署合作协议", "协议签署时间",
                "项目分类", "合作内容", "合作内容主要简介", "本月工作进展情况", "下一步工作计划", "阶段性工作成果", "部门联系人及联系方式", "备注"};
        //获取工作信息数据
        List<WorkInfo> workInfoList = workInfoService.selectWorkExport(queryMap);

        if (workInfoList != null && workInfoList.size() != 0) {

            String[][] dataList = new String[workInfoList.size()][columnName.length];

            for (int i = 0; i < workInfoList.size(); i++) {

                WorkInfo workInfo = workInfoList.get(i);

                //承办部门
                dataList[i][0] = workInfo.getDepartment().getDepartment();
                //合作单位性质
                dataList[i][1] = workInfo.getUnitsNature().getName();
                //合作单位名称
                dataList[i][2] = workInfo.getUnitscooperativename();
                //企业类型
                dataList[i][3] = workInfo.getCooperativeType().getType();
                //企业规模
                dataList[i][4] = workInfo.getScale().getScale();
                //外资属性
                dataList[i][5] = workInfo.getForeignProperty().getProperty();
                //行政区属
                dataList[i][6] = workInfo.getAdministrativeDistrict().getAdministrativedistrict();
                //企业所在地
                dataList[i][7] = workInfo.getEnterpriseLocation().getEnterpriselocation();
                //企业联系人及联系方式
                dataList[i][8] = workInfo.getContactsname();
                //是否签署合作协议
                if (workInfo.getSignagreement().intValue() == 1) {

                    dataList[i][9] = "是";
                } else if (workInfo.getSignagreement().intValue() == 2) {
                    dataList[i][9] = "否";
                }
                //协议签署时间
                dataList[i][10] = DateUtil.dateToStr(workInfo.getSigntime());
                //项目分类
                dataList[i][11] = workInfo.getProjectType().getProjecttype();
                /**
                 * 合作内容，多个内容用分号分割
                 */
                dataList[i][12] = "";
                dataList[i][13] = "";
                List<CooperativeContentRel> cooperativeContentRelList = workInfo.getCooperativeContentRelList();

                for (CooperativeContentRel cooperativeContentRel : cooperativeContentRelList) {

                    dataList[i][12] += cooperativeContentRel.getCooperativeContent().getContent() + ";";
                    //合作内容主要简介，多个内容用分号分割
                    dataList[i][13] += cooperativeContentRel.getBriefintroduction() + ";";

                }

                //本月工作进展情况
                dataList[i][14] = workInfo.getWorkprogress();

                //下一步工作计划
                dataList[i][15] = workInfo.getWorkplan();
                //阶段性工作成果
                dataList[i][16] = workInfo.getWorkplan();
                //部门联系人及联系方式
                dataList[i][17] = workInfo.getDepartmentContactName();
                //备注
                if (workInfo.getRemark() == null || workInfo.getRemark().equals("")) {
                    dataList[i][18] = "";
                } else {
                    dataList[i][18] = workInfo.getRemark();
                }


            }

            //生成文件名
            String fileName = UUID.randomUUID() + ".xls";

            try {
                //导出excel
                ExcelUtil.exportWithResponse(titleName, columnName, dataList, fileName, response);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }


    }

}
